package com.platform.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONObject;
import com.platform.dao.*;
import com.platform.dto.CheckCommissionDetailVo;
import com.platform.entity.*;
import com.platform.util.CommonUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.*;

import static com.platform.config.Constants.*;


@Service
public class ApiOrderService {
    @Autowired
    private ApiOrderMapper orderDao;
    @Autowired
    private ApiAddressMapper apiAddressMapper;
    @Autowired
    private ApiCartMapper apiCartMapper;
    @Autowired
    private ApiCouponMapper apiCouponMapper;
    @Autowired
    private ApiOrderMapper apiOrderMapper;
    @Autowired
    private ApiOrderGoodsMapper apiOrderGoodsMapper;
    @Autowired
    private ApiUserCouponMapper apiUserCouponMapper;
    @Autowired
    private ApiSysMacroService macroService;//通用字典表
    @Autowired
    private ApiInvoiceMapper apiInvoiceMapper;


    //queryByOutTradeNo
    public OrderVo queryByOutTradeNo(@Param("out_trade_no") String out_trade_no) {
        return orderDao.queryByOutTradeNo(out_trade_no);
    }

    public OrderVo queryById(@Param("orderId") Integer orderId) {
        OrderVo orderVo = orderDao.queryById(orderId);

        if (orderVo != null) {
            Date addTime = orderVo.getAdd_time();
            //判断订单是否已经超时支付
            if (orderVo.getOrder_status() == 0) {
                Integer timeLimit = TIME_LIMIT;
                //支付超时时间(秒)
                SysMacroVo macroVo1 = macroService.queryObject((long) 10);
                if (macroVo1 != null) {
                    String value = macroVo1.getValue();
                    if (Validator.isNumber(value)) {
                        timeLimit = Integer.valueOf(value);
                    }
                }
                long between = DateUtil.between(addTime, new Date(), DateUnit.SECOND);
                if (between > timeLimit) {
                    orderVo.setOrder_status(101);
                    orderDao.update(orderVo);
                }
            }
            //更新需要确认收货的订单
            updateConfirmOrder(orderVo.getUser_id());
        }

        return orderDao.queryById(orderId);
    }


    public OrderVo queryObject(Integer id) {
        queryById(id);
        return orderDao.queryObject(id);
    }


    public List<OrderVo> queryList(Map<String, Object> map) {
        return orderDao.queryList(map);
    }


    public int queryTotal(Map<String, Object> map) {
        return orderDao.queryTotal(map);
    }


    public void save(OrderVo order) {
        orderDao.save(order);
    }


    public void update(OrderVo order) {
        orderDao.update(order);
    }


    public void delete(Integer id) {
        orderDao.delete(id);
    }


    public void deleteBatch(Integer[] ids) {
        orderDao.deleteBatch(ids);
    }


    /**
     * 更新当前用户已经超过确认收货日期的订单,订单列表接口用
     */
    public void updateConfirmOrder(@Param("user_id") Long user_id) {
        //todo 更新没有延时确认的订单
        orderDao.updateSimpleConfirmOrder(user_id);

        //todo 更新有延时确认的订单
        orderDao.updateDelayConfirmOrder(user_id);
    }


    /**
     * 更新当前用户过期支付的订单状态为取消,订单列表接口用
     */
    public void updateTimeOutOrder(@Param("user_id") Long user_id) {
        SysMacroVo sysMacroVo = macroService.queryObject((long) 10);//支付超时时间(秒)

        Integer time_limit = TIME_LIMIT;
        if (sysMacroVo != null) {
            String value = sysMacroVo.getValue();
            if (Validator.isNumber(value)) {
                time_limit = Integer.valueOf(value);
            }
        }

        orderDao.updateTimeOutOrder(user_id, time_limit);
    }

    /**
     * 提交订单
     *
     * @param loginUser
     * @param couponId
     * @param couponNumber
     * @param postscript
     * @param addressId
     * @param fullCutCouponDec
     * @return
     */
    @Transactional
    public Map submit(UserVo loginUser,
                      Integer couponId,
                      String couponNumber,
                      String postscript,
                      Integer addressId,
                      BigDecimal fullCutCouponDec,
                      Integer isBilling,
                      Integer invoiceId) {

        Map<String, Object> resultObj = new HashMap<>();

        Long userId = loginUser.getUserId();

        if (fullCutCouponDec == null) {
            fullCutCouponDec = BigDecimal.valueOf(0);
        }

        AddressVo addressVo = apiAddressMapper.queryObject(addressId);

        BigDecimal freightPrice = FREIGHT_PRICE;//默认运费价格为10元

        //采用通用字典中设置的运费
        SysMacroVo sysMacroVo = macroService.queryObject((long) 9);
        if (sysMacroVo != null) {
            String value = sysMacroVo.getValue();
            if (Validator.isNumber(value)) {
                freightPrice = new BigDecimal(value);
            }
        }

        //获取要购买的商品
        Map<String, Object> param = new HashMap<>();
        param.put("user_id", loginUser.getUserId());
        param.put("session_id", 1);
        param.put("checked", 1);
        List<CartVo> checkedGoodsList = apiCartMapper.queryList(param);
        if (null == checkedGoodsList) {
            resultObj.put("errno", 1);
            resultObj.put("errmsg", "请选择商品");
            return resultObj;
        }

        //统计商品总价
        BigDecimal goodsTotalPrice = new BigDecimal(0.00);
        for (CartVo cartItem : checkedGoodsList) {
            if (cartItem.getProduct_status() == 0) {
                resultObj.put("errno", 1);
                resultObj.put("errmsg", cartItem.getProduct_name() + " 已失效");
                return resultObj;
            }
            goodsTotalPrice = goodsTotalPrice.add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber())));
        }

        //获取订单使用的优惠券
        BigDecimal couponPrice = new BigDecimal(0.00);
        if (null != couponId && 0 != couponId) {
            CouponVo couponVo = apiCouponMapper.queryObject(couponId);
            if (null != couponVo && null != couponVo.getType_money()) {
                couponPrice = couponVo.getType_money();//优惠券金额
            }
        }

        // 获取优惠信息提示
        Map<String, Object> couponParam = new HashMap<>();
        couponParam.put("enabled", true);
        Integer[] send_types = new Integer[]{7};
        couponParam.put("send_types", send_types);
        List<CouponVo> couponVos = apiCouponMapper.queryList(couponParam);
        if (null != couponVos && couponVos.size() > 0) {
            for (CouponVo couponVo : couponVos) {
                // 判断是否免运费
                if (couponVo.getSend_type() == 7 && couponVo.getMin_goods_amount().compareTo(goodsTotalPrice) <= 0) {
                    freightPrice = new BigDecimal(0);
                }
            }
        }

        //订单价格计算
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice); //订单的总价
//.subtract(fullCutCouponDec)
        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);  //减去其它支付的金额后，要实际支付的金额

        //创建OrderVo对象
        OrderVo orderInfo = new OrderVo();
        orderInfo.setOrder_sn(CommonUtil.generateOrderNumber());
        orderInfo.setUser_id(loginUser.getUserId());
        //收货地址和运费
        orderInfo.setConsignee(addressVo.getUserName());
        orderInfo.setMobile(addressVo.getTelNumber());
        orderInfo.setProvince(addressVo.getProvinceName());
        orderInfo.setCity(addressVo.getCityName());
        orderInfo.setDistrict(addressVo.getCountyName());
        orderInfo.setAddress(addressVo.getDetailInfo());
        orderInfo.setFreight_price(freightPrice.intValue());
        orderInfo.setIs_delete(0);
        orderInfo.setIs_delay(0);
        //留言
        orderInfo.setPostscript(postscript);

        //使用的优惠券
        orderInfo.setFull_cut_price(fullCutCouponDec);
        orderInfo.setCoupon_id(couponId);
        orderInfo.setCoupon_price(couponPrice);
        orderInfo.setAdd_time(new Date());
        orderInfo.setGoods_price(goodsTotalPrice);
        orderInfo.setOrder_price(orderTotalPrice);
        orderInfo.setActual_price(actualPrice);

        // 待付款
        orderInfo.setOrder_status(0);
        orderInfo.setShipping_status(0);
        orderInfo.setPay_status(0);
        orderInfo.setShipping_id(0);
        orderInfo.setShipping_fee(new BigDecimal(0));
//        orderInfo.setIntegral((int) actualPrice.floatValue());//积分
        orderInfo.setIntegral(0);//积分
        orderInfo.setIntegral_money(new BigDecimal(0));//积分抵扣金额

        //保存发票信息
        orderInfo.setIs_billing(isBilling);

        if (isBilling == 1) {
            InvoiceVo invoiceVo = apiInvoiceMapper.queryObject(invoiceId);
            orderInfo.setInvoice_type(invoiceVo.getInvoiceType());
            orderInfo.setHeader_type(invoiceVo.getHeaderType());
            orderInfo.setHeader_content(invoiceVo.getHeaderContent());
            orderInfo.setContent_type(invoiceVo.getContentType());
            orderInfo.setInvoicer_mobile(invoiceVo.getInvoicerMobile());
            orderInfo.setInvoicer_email(invoiceVo.getInvoicerEmail());
            orderInfo.setTaxpayer_identification_number(invoiceVo.getTaxpayerIdentificationNumber());
        }

        //开启事务，插入订单信息和订单商品
        apiOrderMapper.save(orderInfo);
        if (null == orderInfo.getId()) {
            resultObj.put("errno", 1);
            resultObj.put("errmsg", "订单提交失败");
            return resultObj;
        }


        //记录订单产品
//        List<OrderGoodsVo> orderGoodsData = new ArrayList<>();
        for (CartVo goodsItem : checkedGoodsList) {
            OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
            orderGoodsVo.setOrder_id(orderInfo.getId());
            orderGoodsVo.setGoods_id(goodsItem.getGoods_id());
            orderGoodsVo.setGoods_sn(goodsItem.getGoods_sn());
            orderGoodsVo.setProduct_id(goodsItem.getProduct_id());
            orderGoodsVo.setGoods_name(goodsItem.getGoods_name());
            orderGoodsVo.setProduct_name(goodsItem.getProduct_name());
            orderGoodsVo.setProduct_pic_url(goodsItem.getProduct_pic_url());
            orderGoodsVo.setList_pic_url(goodsItem.getList_pic_url());
            orderGoodsVo.setMarket_price(goodsItem.getMarket_price());
            orderGoodsVo.setRetail_price(goodsItem.getRetail_price());
            orderGoodsVo.setNumber(goodsItem.getNumber());
            orderGoodsVo.setGoods_specifition_name_value(goodsItem.getGoods_specifition_name_value());
            orderGoodsVo.setGoods_specifition_ids(goodsItem.getGoods_specifition_ids());
            apiOrderGoodsMapper.save(orderGoodsVo);
            //   orderGoodsData.add(orderGoodsVo);
        }

        //清空已购买的商品
        apiCartMapper.deleteByCart(loginUser.getUserId(), 1, 1);
        resultObj.put("errno", 0);
        resultObj.put("errmsg", "订单提交成功");

        //
        Map<String, Object> orderInfoMap = new HashMap<>();
        orderInfoMap.put("orderInfo", orderInfo);

        resultObj.put("data", orderInfoMap);

        // 优惠券标记已用
        if (!StringUtils.isEmpty(couponNumber)) {
            UserCouponVo userCouponVo = apiUserCouponMapper.queryByCouponNumber(couponNumber);
            if (null != userCouponVo && null == userCouponVo.getOrder_id()) {
                userCouponVo.setUsed_time(new Date());
                userCouponVo.setOrder_id(orderInfo.getId());
                userCouponVo.setIs_used(1);
                apiUserCouponMapper.update(userCouponVo);
            }
        }

        return resultObj;
    }


    public BigDecimal checkActualPrice(Long user_id) {
        return orderDao.checkActualPrice(user_id);
    }

    public BigDecimal checkLastMonthActualPrice(Long user_id) {
        return orderDao.checkLastMonthActualPrice(user_id);
    }

    public OrderVo queryTheLatestCompletedOrders(Long user_id) {
        return orderDao.queryTheLatestCompletedOrders(user_id);
    }

    public CheckCommissionDetailVo checkCommissionDetailByMonth(@Param("user_id") Long user_id, @Param("detail_month") String detailMobth) {
        return orderDao.checkCommissionDetailByMonth(user_id, detailMobth);
    }

    //查询最新的订单
    public OrderVo queryNewestOrder(Map<String, Object> params) {
        return orderDao.queryNewestOrder(params);
    }

}
